<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 平台佣金
 * Class Controller_Admin_Finance_Commission_Index
 */
class Controller_Admin_Finance_Commission_Index extends Stourweb_Controller
{
    public function before()
    {
        parent::before();
        //右侧导航
        $this->assign('parentkey', $this->params['parentkey']);
        $this->assign('prefix_url','finance/admin/finance/commission');
    }


    //返佣栏目设置
    public function action_config_commission_type()
    {
        $productlist = Model_Member_Order_Extend::get_commission_product();
        $list=ORM::factory('supplier_commission_config')->get_all();
        $info=array();
        foreach($list as $v)
        {
            $info[$v['varname']]=$v['value'];
        }
        $this->assign('info',$info);
        $this->assign('productlist',$productlist);
        $this->display('admin/finance/commission/commission_type');

    }

    //返佣产品类型分佣设置
    public function action_ajax_config_commission_type_save()
    {
        $productlist = Model_Member_Order_Extend::get_commission_product();
        $config = array('type', 'ratio', 'cash');
        $varname_arr    = array();
        foreach($productlist as $p)
        {
            foreach($config as $c)
            {
                $varname_arr[]  = "cfg_commission_{$c}_".$p['id'];
            }
            if($p['id'] == 1)
            {
                $varname_arr[] = 'cfg_commission_cash_1_old';
                $varname_arr[] = 'cfg_commission_cash_1_child';
                $varname_arr[] = 'cfg_commission_cash_1_people4';
               $varname_arr[] = 'cfg_commission_cash_1_people5';
               $varname_arr[] = 'cfg_commission_cash_1_people6';
            }
        }

        // 现金返佣时,佣金计算规则
        $varname_arr[] = 'cfg_commission_cash_calc_type';
        foreach($varname_arr as $varname)
        {
            $value = Arr::get($_POST, $varname);
            $value = intval($value);
            Model_Supplier_Commission_Config::save_normal_config($varname, $value);
        }
        echo json_encode(array('status' => true));
    }

    //返佣具体产品设置
    public function action_config_commission_product()
    {
        $action = $this->params['action'];
        $typeid = $this->params['typeid'];
        $menuid = $this->params['menuid'];
        if(empty($action))
        {
            $supplier_list = DB::query(Database::SELECT, "SELECT id,suppliername FROM sline_supplier WHERE find_in_set({$typeid},authorization)")->execute()->as_array();
            $productlist = Model_Member_Order_Extend::get_commission_product();
            $this->assign('typeid', $typeid);
            $this->assign('supplier_list', $supplier_list);
            $this->assign('products', $productlist);
            $this->assign('menuid', $menuid);
            if ($typeid == 1)
            {
                $people_group = Model_Sysconfig::get_people_group();
                $this->assign('people_group',$people_group);
                $this->display('admin/finance/commission/commission_product_line');
            } else
            {
                $this->display('admin/finance/commission/commission_product');
            }
        }
        elseif($action == 'read')
        {

            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $keyword = Arr::get($_GET, 'keyword');
            $supplier = Arr::get($_GET, 'supplier');
            $sort = json_decode(Arr::get($_GET, 'sort'), true);
            $order = 'order by a.modtime desc,a.addtime desc';

            $keyword = Common::getKeyword($keyword);
            $table= $this->_get_table($typeid);
            $ftable='sline_'.$table;

            $fields='a.title,a.webid,a.id,a.aid,a.modtime,b.commission_type,b.commission_ratio,b.commission_cash,b.commission_cash_child,b.commission_cash_old,b.commission_cash_people4,b.commission_cash_people5,b.commission_cash_people6';
            if(empty($table))
                return;
            if ($sort[0]['property'])
            {
                $property=$sort[0]['property'];
                $ratioFields=array('commission_type','commission_ratio','commission_cash');
                if(in_array($property,$ratioFields))
                    $orderStr = "b.{$property} {$sort[0]['direction']}";
                if($property=='modtime')
                    $orderStr = "a.modtime {$sort[0]['direction']}";
                $order=" order by {$orderStr},a.modtime desc,a.addtime desc";

            }
            $w = "where a.id is not null and c.suppliertype=1"; //第三方供应商
            //线路,酒店,商城必须要求上架状态.
            if(in_array($typeid,array(1,2,21)))
            {
                $w.= " and a.status = 3";
            }
            $w.= $table=='model_archive'?" and a.typeid={$typeid} ":"";
            $w .= !empty($keyword)? " and (a.id='{$keyword}' or a.title like '%{$keyword}%')":'';
            $w .= !empty($supplier)? " and c.id=$supplier":'';


            $sql = "select {$fields} from {$ftable} a left join sline_supplier_commission_product b on a.id=b.productid and b.typeid={$typeid} left join  sline_supplier c on a.supplierlist=c.id $w $order limit  $start,$limit";

            if($typeid==5)
            {
                $sql = "select {$fields} from sline_spot a INNER JOIN sline_spot_ticket d on a.id=d.spotid left join sline_supplier_commission_product b on a.id=b.productid and b.typeid=5 left join  sline_supplier c on d.supplierlist=c.id $w  group by a.id $order limit $start,$limit";
            }


            //echo $sql;exit;

            $sql_num = "select count(*) as num from {$ftable} a left join  sline_supplier c on a.supplierlist=c.id $w";
            if($typeid==5)
            {
                $sql_num = "select count(distinct(a.id)) as num from sline_spot a INNER JOIN sline_spot_ticket d on a.id=d.spotid left join sline_supplier_commission_product b on a.id=b.productid and b.typeid=5 left join  sline_supplier c on d.supplierlist=c.id $w ";
            }
            $totalcount_arr = DB::query(Database::SELECT, $sql_num)->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach($list as $k=>&$v)
            {
                $v['url']=$this->_get_url($typeid,$v['webid'],$v['aid'],$v['id']);
                $v['modtime'] = empty($v['modtime'])?'':date('Y-m-d',$v['modtime']);
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        elseif($action == 'update')
        {
            $id = $_POST['id'];
            $field = $_POST['field'];
            $val = $_POST['val'];
            $typeid = $_POST['typeid'];
            if(empty($id) || empty($typeid))
            {
                echo 'no';
                return;
            }
            $curtime=time();
            $ratioModel=ORM::factory('supplier_commission_product')->where('typeid','=',$typeid)->and_where('productid','=',$id)->find();
            $ratioModel->typeid=$typeid;
            $ratioModel->productid=$id;
            $ratioModel->$field=abs($val);
            $ratioModel->modtime=$curtime;
            $ratioModel->save();
            echo 'ok';
        }
        elseif($action == 'updatesome')
        {
            $id = $_POST['id'];
            $typeid = $_POST['typeid'];
            $commission_type = $_POST['commission_type'];
            $commission_ratio = $_POST['commission_ratio'];
            $commission_cash = $_POST['commission_cash'];
            $commission_cash_child = $_POST['commission_cash_child'];
            $commission_cash_old = $_POST['commission_cash_old'];
            $commission_cash_people4 = $_POST['commission_cash_people4'];
            $commission_cash_people5 = $_POST['commission_cash_people5'];
            $commission_cash_people6 = $_POST['commission_cash_people6'];


            if(empty($id) || empty($typeid))
            {
                echo 'no';
                return;
            }
            $curtime=time();
            $ratioModel=ORM::factory('supplier_commission_product')->where('typeid','=',$typeid)->and_where('productid','=',$id)->find();
            $ratioModel->typeid=$typeid;
            $ratioModel->productid=$id;
            $ratioModel->commission_type=abs($commission_type);
            $ratioModel->commission_ratio=abs($commission_ratio);
            $ratioModel->commission_cash=abs($commission_cash);
            $ratioModel->commission_cash_child=abs($commission_cash_child);
            $ratioModel->commission_cash_old=abs($commission_cash_old);
            $ratioModel->commission_cash_people4=abs($commission_cash_people4);
            $ratioModel->commission_cash_people5=abs($commission_cash_people5);
            $ratioModel->commission_cash_people6=abs($commission_cash_people6);
            $ratioModel->modtime=$curtime;
            $ratioModel->save();
            echo 'ok';
        }


    }

    //获取表名
    private function _get_table($typeid)
    {
        $model=ORM::factory('model',$typeid);
        if(!$model->loaded())
            return false;
        return $model->maintable;
    }
    //获取产品URL
    private function _get_url($typeid,$webid,$aid,$id)
    {
        $model = ORM::factory('model', $typeid);
        if (!$model->loaded())
        {
            return false;
        }
        $webid = empty($webid) ? 0 : $webid;
        $realid = $typeid == 101 ? $id : $aid;
        $url_folder = empty($model->correct) ? $model->pinyin : $model->correct;
        $url = Common::getBaseUrl($webid) . '/' . $url_folder . '/show_' . $realid . '.html';
        return $url;
    }

}